package com.edais.service.imp;

import com.edais.domain.gift.GiftPackageOrder;
import com.edais.service.GiftPackageExchangeFunction;
import com.edais.service.gift.GiftPackageOrderService;
import com.edais.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class GiftPackageExchangeFunctionInvoke {

	@Autowired
	ApplicationContext context;

	@Autowired
	private GiftPackageOrderService packageOrderService;

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public Map<String,String>  apply(String id, Map<String,Object> param) throws Exception {
        if(null == id)
            throw new NullPointerException("id is null");
		if(!param.containsKey("userId") || null == param.get("userId"))
			throw new NullPointerException("userId is null");
		if(!param.containsKey("mobile") || null == param.get("mobile"))
			throw new NullPointerException("mobile is null");
		Map<String,Object> orderParams = new HashMap<String,Object>();
		orderParams.put("id",Long.valueOf(id));
		orderParams.put("userId",param.get("userId"));
		GiftPackageOrder packageOrder = this.packageOrderService.selectGiftPackageOrder(orderParams);
        if(null == packageOrder)
            throw new NullPointerException("packageOrder is null, id = " + id);
		GiftPackageExchangeFunction packageExFunction = (GiftPackageExchangeFunction) context
				.getBean(packageOrder.getPackageExchangeServiceName());

		if(!StringUtils.isEmpty(packageOrder.getPackageExchangeServiceParam())){
			param.putAll(JsonUtil.getMapFromJsonString(packageOrder.getPackageExchangeServiceParam()));
		}
		param.put("packageOrder",packageOrder);
		return packageExFunction.apply(param);
	}
}